package com.rc.saas.mini.controller.member;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.member.MemberAccount;
import com.rc.saas.mini.model.member.MemberAccountRecord;
import com.rc.saas.mini.model.member.MemberAccountRecordExample;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberShareService;
import com.rc.saas.mini.service.member.MemberAccountRecordService;
import com.rc.saas.mini.service.member.MemberAccountService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.vo.member.MemberAccountVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author wangzhengwei
 * @create 2021/4/26
 */
@Api(tags = "15.钱包相关")
@Controller
@RequestMapping("/memberAccount")
public class MemberAccountController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(MemberAccountController.class);

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private EnterpriseSubmemberShareService enterpriseSubmemberShareService;

    @Autowired
    private MemberAccountRecordService memberAccountRecordService;

    /**
     * 人钱包 1 企业钱包 2权益金 3收益金 默认0',
     * 我的账户->账户记录
     */
    @ResponseBody
    @RequestMapping("/listPageAccount")
    @ApiOperation(value = "账户记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", paramType = "query", value = "", required = false),
            @ApiImplicitParam(name = "yearMonth", paramType = "query", value = "年月(yyyy-MM)", required = false),
            @ApiImplicitParam(name = "accountType", paramType = "query", value = " 0个人钱包 2权益金 3收益金,4全部，默认全部", required = false),
            @ApiImplicitParam(name = "recordType", paramType = "query", value = " 0会员在线充值（充值）, 5平台赠送（活动送充值），14后台退款 （提现） 默认全部", required = false),
            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "", required = false)})
    public DataTResponse<PageInfo<MemberAccountRecord>> listPageAccount(HttpServletRequest request,
                                                                        @RequestParam(value = "accountType", defaultValue = "4") String accountType,
                                                                        @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                                        String yearMonth,
                                                                        String recordType,
                                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        String tenantCode = loginInfo.getTenantCode();
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        if(recordType!=null&&"".equals(recordType)){
            recordType=null;
        }

        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if("4".equals(accountType)){
            accountType=null;
        }
        logger.info("MemberAccountController.listPageAccountDate.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        PageHelper.startPage(pageNo, pageSize);
        MemberAccountRecordExample example = new MemberAccountRecordExample();

        List<MemberAccountRecord> list = memberAccountRecordService.listByTypeAndMonth(member.getMemberId(), accountType, yearMonth,recordType);

        return DataTResponse.SUCCESS_DATA(new PageInfo<MemberAccountRecord>(list));
    }

    /**
     * 我的账户页面
     */
    @RequestMapping("/selectMemberAccount")
    @ResponseBody
    @ApiOperation(value = "我的账户", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<MemberAccountVo> selectMemberAccount(HttpServletRequest request) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        String tenantCode = loginInfo.getTenantCode();
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }

        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("MemberAccountController.selectMemberAccount.tenantCode:{},mobile:{}", tenantCode, member.getMobile());

        MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(member.getMemberId());

        MemberAccountVo memberAccountVo = new MemberAccountVo();
        BeanUtils.copyProperties(memberAccount, memberAccountVo);

        List<MemberAccountRecord> yesterdayRecord=memberAccountRecordService.listByYesterday(member.getMemberId());
        List<MemberAccountRecord> monthRecord=memberAccountRecordService.listByGetMonth(member.getMemberId());
        memberAccountVo.setYesterdayAccount(yesterdayRecord.stream().map(MemberAccountRecord::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add));
        memberAccountVo.setMonthAccount(monthRecord.stream().map(MemberAccountRecord::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add));
        memberAccountVo.setAllAccount(memberAccount.getAccount().add(memberAccount.getIncomeAmount()));
        return DataTResponse.SUCCESS_DATA(memberAccountVo);
    }

    ///**
    // * 我的账户->账户记录
    // */
    //@ResponseBody
    //@RequestMapping("/listPageAccountDate")
    //@ApiOperation(value = "账户记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "pageNo", paramType = "query", value = "", required = false),
    //        @ApiImplicitParam(name = "accountType", paramType = "query", value = " 0个人钱包 1 企业钱包 2权益金 3收益金,4全部，默认全部", required = false),
    //        @ApiImplicitParam(name = "pageSize", paramType = "query", value = "", required = false)})
    //public TResponse listPageAccountDate(@ApiIgnore HttpSession session,
    //                                     @RequestParam(value = "accountType", defaultValue = "4") String accountType,
    //                                     @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
    //                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return TResponse.FAIL("找不到对应运营商信息");
    //    }
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
    //    if (member == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    logger.info("MemberAccountController.listPageAccountDate.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
    //
    //    PageInfo<String> accountRecords = memberAccountRecordService.listPageMemberAccountDateRecord(member.getMemberId(), pageSize, pageNo);
    //
    //    return TResponse.SUCCESS_DATA(accountRecords);
    //}

    ///** 账户明细 */
    //@ResponseBody
    //@RequestMapping("/listPageAccountRecord")
    //@ApiOperation(value = "账户明细", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "yearMonth", paramType = "query", value = "年月(yyyy-MM)", required = true)})
    //public TResponse listPageAccountRecord(@ApiIgnore HttpSession session, String yearMonth) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return TResponse.FAIL("找不到对应运营商信息");
    //    }
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
    //    if (member == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    logger.info("MemberAccountController.listPageAccountDate.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
    //
    //    if (yearMonth == null) {
    //        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
    //        Date date = new Date();
    //        yearMonth = format.format(date);
    //    }
    //    List<MemberAccountRecord> accountRecords = memberAccountRecordService.listMemberAccountRecord(member.getMemberId(), yearMonth);
    //    return TResponse.SUCCESS_DATA(accountRecords);
    //}

}
